package com.cqcj.login.web;

import com.cqcj.login.pojo.User;
import com.cqcj.login.service.RegisterService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        RegisterService registerService = new RegisterService();
        //获取用户名与密码,验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");//验证码

        //从session找到验证码，比较输入的验证码是否等于session中的验证码
        //获取session对象
        HttpSession session = request.getSession();
        //获取值
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        User user = registerService.selectByUsername(username);
        if (checkCode.equalsIgnoreCase(checkCodeGen)) {//此方法比对可忽略大小写
            if (user != null) {//相同返回用户名已存在
                request.setAttribute("username_err","用户名已存在");
                request.getRequestDispatcher("/register.jsp").forward(request, response);//转发
            } else {
                //验证码相同就去数据库添加
                User user1 = new User();
                user1.setUsername(username);
                user1.setPassword(password);
                boolean flag = registerService.register(user1);//默认调用就成功
                if(flag){
                    request.getRequestDispatcher("/login.jsp").forward(request, response);//转发
                }
            }
        }else {
            request.setAttribute("checkCode_err", "验证码不正确");
            request.getRequestDispatcher("/register.jsp").forward(request, response);//转发
        }
    }
}
